'use client'
import { useParams, useRouter } from 'next/navigation'
import { Table, message, Button, Breadcrumb, Modal, Image, Space } from 'antd'
import { useState, useEffect } from 'react'
import { ArrowLeftOutlined, HomeOutlined } from '@ant-design/icons'
import styles from './styles.module.css'
import clsx from 'clsx';
import { scanAgentApi, DetailData } from '@/services/api';

// 页面标题映射
const PAGE_TITLES: { [key: string]: string } = {
  'accident-monitoring': '交通事故监测',
  'violation-detection': '违规行为识别',
  'traffic-flow': '交通流量监测与预测',
  'network-monitoring': '网络监测与诊断',
  'pedestrian-safety': '行人与非机动车安全监控',
  'parking-management': '停车秩序管理',
  'road-analysis': '道路隐患分析'
}

const DetailPage = () => {
  const params = useParams()
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState<DetailData[]>([])
  const [viewModalVisible, setViewModalVisible] = useState(false)
  const [pushModalVisible, setPushModalVisible] = useState(false)
  const [selectedRecord, setSelectedRecord] = useState<DetailData | null>(null)

  const pageTitle = PAGE_TITLES[params.type as string] || '详情列表'

  const handleBack = () => {
    router.back()
  }

  const handleHomeClick = () => {
    router.push('/scan-agent')
  }

  const handleListClick = () => {
    router.push('/scan-agent')
  }

  const handleView = (record: DetailData) => {
    setSelectedRecord(record)
    setViewModalVisible(true)
  }

  const handleDownloadReport = async (record: DetailData) => {
    try {
      message.loading('报告下载中...')
      await scanAgentApi.downloadReport(record.id)
      message.success('报告下载成功')
    } catch (error) {
      message.error('报告下载失败，请稍后重试')
    }
  }

  const handlePush = (record: DetailData) => {
    setSelectedRecord(record)
    setPushModalVisible(true)
  }

  const handlePushConfirm = async () => {
    try {
      message.loading('推送中...')
      if (selectedRecord) {
        await scanAgentApi.pushData(selectedRecord)
        message.success('推送成功')
        setPushModalVisible(false)
      }
    } catch (error) {
      message.error('推送失败，请稍后重试')
    }
  }

  const columns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
    },
    {
      title: '地点',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '操作',
      key: 'operation',
      render: (_: any, record: DetailData) => {
        return (
          <Space size="middle">
            <a onClick={() => handleView(record)}>查看</a>
            <a onClick={() => handleDownloadReport(record)}>报告下载</a>
            <a onClick={() => handlePush(record)}>一键推送</a>
          </Space>
        )
      },
    },
  ]

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        const result = await scanAgentApi.getDetails(params.type as string)
        setData(result)
      } catch (error) {
        // 模拟数据
        setData([
          {
            id: '1',
            timestamp: '2024-03-20 10:30:00',
            location: '中山路与解放路路口',
            status: '已处理',
            description: '车辆违规停放',
          },
          {
            id: '2',
            timestamp: '2024-03-20 11:15:00',
            location: '人民广场东门',
            status: '处理中',
            description: '交通信号灯故障',
          },
        ])
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [params.type])

  return (
    <div className={styles.anentList}>
      <div className={styles.bread}>
        <Breadcrumb
          items={[
            {
              title: <span className= {styles.back}onClick={handleListClick}>场景列表</span>,
            },
            {
              title: <span className={styles.currentRoute} >{pageTitle}</span>,
            },
          ]}
        />
      </div>
      <div className={styles.analysis}>
          <div className={clsx(styles.item, styles.totalBg)}>
            <div>
              <span className={styles.title}>22</span>
              <div className={styles.desc}>累计事故数</div>
            </div>
          </div>
          <div className={clsx(styles.item, styles.trendBg)}>
            <div>
              <span className={styles.title}>30</span>
              <span className={styles.title}>min</span>
              <div className={styles.desc}>事故变化趋势</div>
            </div>
          </div>
          <div className={clsx(styles.item, styles.timeBg)}>
            <div>
              <span className={styles.title}>22</span>
              <div className={styles.desc}>事故平均响应时间</div>
            </div>
          </div>
          <div className={clsx(styles.item, styles.locationBg)}>
            <div>
              <span className={styles.roadTitle}>衡阳大道与蒸湘路交叉口</span>
              <div className={styles.desc}>事故高发位置</div>
            </div>
          </div>
      </div>
      <div className={styles.table}>
       <Table
        columns={columns}
        dataSource={data}
        loading={loading}
        rowKey="id"
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />
      </div>
     

      <Modal
        title="详情查看"
        open={viewModalVisible}
        onCancel={() => setViewModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedRecord && (
          <div>
            <div style={{ marginBottom: 20 }}>
              <Image
                src="/images/traffic-detail.jpg"
                alt="交通详情"
                style={{ width: '100%', maxHeight: 400, objectFit: 'cover' }}
              />
            </div>
            <div style={{ marginBottom: 16 }}>
              <h3>事件信息</h3>
              <p>时间：{selectedRecord.timestamp}</p>
              <p>地点：{selectedRecord.location}</p>
              <p>状态：{selectedRecord.status}</p>
              <p>描述：{selectedRecord.description}</p>
            </div>
            <div>
              <h3>AI分析结果</h3>
              <p>违规类型：闯红灯</p>
              <p>置信度：98%</p>
              <p>建议处理：立即处罚</p>
            </div>
          </div>
        )}
      </Modal>

      <Modal
        title="一键推送"
        open={pushModalVisible}
        onOk={handlePushConfirm}
        onCancel={() => setPushModalVisible(false)}
      >
        <div style={{ marginBottom: 16 }}>
          <h4>推送目标</h4>
          <div style={{ marginBottom: 8 }}>
            <input type="checkbox" checked disabled /> 执法中心
          </div>
          <div style={{ marginBottom: 8 }}>
            <input type="checkbox" checked disabled /> 交管媒体
          </div>
          <div>
            <input type="checkbox" checked disabled /> 其他部门
          </div>
        </div>
        <div>
          <h4>推送内容</h4>
          <p>时间：{selectedRecord?.timestamp}</p>
          <p>地点：{selectedRecord?.location}</p>
          <p>描述：{selectedRecord?.description}</p>
        </div>
      </Modal>
    </div>
  )
}

export default DetailPage 